package cn.jinjimi.app.presenter;

import android.content.Context;

import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.controller.event.UploadContactStateEvent;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.iview.InputCustomView;
import cn.jinjimi.app.custom.manager.CustomsManager;
import cn.jinjimi.app.interfaces.IView;
import cn.jinjimi.app.store.DatabaseManager;
import cn.jinjimi.app.store.dao.ContactInfoDao;
import cn.jinjimi.app.store.entity.custom.ContactInfo;
import cn.jinjimi.app.main.dialog.LoadingDialog;
import cn.jinjimi.app.util.AddressUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;

/**
 * Created by libilang on 15/11/4.
 */
public class InputCustomPresent extends NetBasePresenter {

    private Context mContext;
    private InputCustomView mView;

    public InputCustomPresent(IView view, Context context) {
        super(view);
        mView = (InputCustomView) view;
        mContext = context;
    }

    /**
     * 判断当前用户是否已导入过,是否需要导入 true 表示已导入过或不需要导  入
     * 如果多个号码，所有的号码都已存在，则该客户为已导入，不再导入
     * 如果只是部分手机码号已存在，则更新老客户信息
     * 如果客户为空，或者手机号码为空，则不需要导入*
     *
     * @param c
     * @return
     */
    public boolean hasInputed(Custom c) {
        if (c != null && c.getContactInfos() != null && c.getContactInfos().size() > 0) {
            for (ContactInfo customPhone : c.getContactInfos()) {
                if (DatabaseManager.getInstance().getContactInfoDao().queryBuilder()
                        .where(ContactInfoDao.Properties.Value.eq(customPhone.getValue()))
                        .where(ContactInfoDao.Properties.SsoId.eq(AccountManager.getInstance().getAccount().ssoid))
                        .count() > 0)
                    return true;
            }
        }
        return false;
    }

    /**
     * 获取所有客户
     */
    public void getCustoms() {
        Task.callInBackground(new Callable<List<Custom>>() {
            @Override
            public List<Custom> call() throws Exception {
                List<Custom> allCustoms = AddressUtils.findAll(mContext); //  从通讯录获取
                for (Custom c : allCustoms) {
                    c.isInput = hasInputed(c);
                }
                return allCustoms;
            }
        }).continueWith(new Continuation<List<Custom>, Void>() {
            @Override
            public Void then(Task<List<Custom>> task) throws Exception {
                mView.getCustomSucc(task.getResult());
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);
    }

    /**
     * 导入客户
     *
     * @param customs 需要导入上传的Custom列表
     */
    public void upLoad(List<Custom> customs) {
        CustomsManager.getInstance().uploadCustoms(customs);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadContactStateEvent(UploadContactStateEvent event) {
        switch (event.uploadState) {
            case LOAD_START:
                LoadingDialog loadingDialog = LoadingDialog.show(mContext, mContext.getString(R.string.upload_contacts_uploading));
                loadingDialog.setCancelable(false);
                loadingDialog.setCanceledOnTouchOutside(false);
                break;
            case LOAD_END:
                break;
            case NOTHING_UPLOAD:
                LoadingDialog.dispose();
                mView.showToast(R.string.upload_contacts_loaded);
                break;
            case LOAD_FAIL:
                mView.loadFail();
                break;
            case UPLOAD_START:  //开始上传服务器
                break;
            case UPLOAD_FAIL:  //上传失败
                LoadingDialog.dispose();
                mView.showToast(R.string.upload_contacts_upload_fail);
                break;
            case UPLOAD_SUCC:  //上传服务器成功
                LoadingDialog.dispose();
                if (event.data != null) {
                    if (event.data.success > 0 && event.data.fails > 0) { //有的成功，有的失败
                        mView.uploadSuccess();
                        ToastUtils.toastMessage(mContext, String.format(mContext.getResources().getString(R.string.upload_contacts_upload_suc_fail), event.data.success, event.data.fails));
                    } else if (event.data.fails == 0) {
                        mView.uploadSuccess();
                        mView.showToast(R.string.upload_contacts_upload_done);
                    } else if (event.data.success == 0) {
                        mView.showToast(R.string.upload_contacts_upload_fail);
                    }
                }
                break;
        }
    }
}
